package temp;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author wangxi created on 2021/6/27 18:18
 * @version v1.0
 */
@Slf4j
public class ProducerConsumer {

    public static Queue<Integer> queue = new LinkedList<>();

    public static int cap = 50;

    private void produce() throws InterruptedException {
        while (true) {

            synchronized (queue) {
                while (queue.size() == cap) {
                    queue.wait();
                }
                Thread.sleep(200);
                queue.offer(1);
                log.info("produce a element. queue.size = " + queue.size());
                queue.notify();
            }
        }
    }

    private void consume() throws InterruptedException {
        while (true) {

            synchronized (queue) {
                while (queue.size() <= 0) {
                    queue.wait();
                }
                Thread.sleep(200);
                queue.poll();
                log.info("consume a element. queue.size = " + queue.size());
                queue.notify();
            }
        }
    }

    public static void main(String[] args) {
        ProducerConsumer obj = new ProducerConsumer();
        new Thread(() -> {
            try {
                obj.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                obj.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
